import request from '@/utils/request'
import axios from 'axios'
import store from '@/store'

export function exportXlsx(url, params) {
  const new_headers = { 'Authorization': 'bearer ' + store.getters.token }
  axios({ url: process.env.BASE_API + url,
    method: 'get',
    headers: new_headers,
    params: params == null ? {} : Object.assign({}, params),
    responseType: 'blob' })
    .then(res => {
      console.log(res)
      var file_name
      if (res.headers.hasOwnProperty('content-disposition')) {
        // 获取服务器 回传的 文件名
        file_name = window.decodeURI(res.headers['content-disposition'].split('filename=')[1])
      } else {
        file_name = '导出数据.xlsx'
      }
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', file_name)
      document.body.appendChild(link)
      link.click()
    }).catch(res => {
      alert(res)
    })
}

// 第二版本的异步请求
// get 请求数据
export function getAjax(url, params) {
  return request({
    url: url,
    method: 'get',
    params: params == null ? {} : Object.assign({}, params)
  })
}
// post 提交数据
export function postAjax(url, data) {
  return request({
    url: url,
    method: 'post',
    data: data == null ? {} : Object.assign({}, data)
  })
}
// patch 修改数据
export function patchAjax(url, data) {
  return request({
    url: url,
    method: 'patch',
    data: data == null ? {} : Object.assign({}, data)
  })
}
// put 修改数据
export function putAjax(url, data) {
  return request({
    url: url,
    method: 'put',
    data: data == null ? {} : Object.assign({}, data)
  })
}
// delete 删除数据
export function deleteAjax(url, data) {
  return request({
    url: url,
    method: 'delete',
    data: data == null ? {} : Object.assign({}, data)
  })
}

